package com.zzyq.pc.mongodb.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Splitter;
import com.zzyq.pc.common.StandardDataFormat;
import com.zzyq.pc.common.base.BaseController;
import com.zzyq.pc.common.plugin.db.PageView;
import com.zzyq.pc.mongodb.Service.IMonitoringService;
import com.zzyq.pc.mongodb.model.MongodbDate;
import com.zzyq.pc.utils.DateSyncUtil;
import com.zzyq.pc.utils.EncodingUtils;
import com.zzyq.pc.utils.ExcelUtils;
import com.zzyq.pc.utils.HttpUtils;
import com.zzyq.pc.utils.LoggerUtils;
import com.zzyq.pc.utils.StringUtil;

@Controller
@RequestMapping(value="/Monitoring/",produces="application/json;charset=UTF-8")
public class MonitoringController extends BaseController{

	@Autowired
	IMonitoringService monitoringService;

	/**
	 * 监控——舆情概况
	 * @param pageIndex
	 * @param pageSize
	 * @param endTime
	 * @param startTime
	 * @param userId
	 * @param ifmId
	 */
	@ResponseBody
	@RequestMapping("GeneralSituation")
	public String findGeneralSituation(HttpServletRequest request,HttpServletResponse response,
			Integer pageIndex,Integer pageSize,String startDate,String endDate,String ifmId){
		List<MongodbDate> list = new ArrayList<MongodbDate>();
		StandardDataFormat dateFormat = new StandardDataFormat(CODE_ERROR, MSG_ERROR, list);
		List<String> ifmIds = new ArrayList<String>();
		//int count = 0;
		//int number = 0;
		Date endTime1 = null;
		Date startTime1 = null;
		PageView pageView = null;
		try {
			if (null == pageIndex || pageIndex <=0) {
				pageIndex = 1;
			}
			if (null == pageSize || pageSize <=0) {
				pageSize = 15;
			}
			if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
				endTime1 = DateSyncUtil.parse(endDate);
				startTime1 = DateSyncUtil.parse(startDate);
			}
			if (StringUtils.isNotBlank(ifmId)) {
				ifmIds = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(ifmId);
			}
			pageView = new PageView(pageSize, pageIndex);
			//long l = System.currentTimeMillis();
			list = monitoringService.findGeneralSituation(pageView, startTime1, endTime1, ifmIds);
			//System.out.println(System.currentTimeMillis()-l);
			/*if (list.size()>0) {
				//拿到总页数
				count = list.get(0).getCount();
				//计算有多少页
				number = count % pageView.getPageSize() == 0 ? count
						/ pageView.getPageSize() : count
						/ pageView.getPageSize() + 1;
			}*/
		} catch (Exception e) {
			LoggerUtils.fmtError(getClass(), "查询错误", e.getMessage());
			e.printStackTrace();
			System.out.println(e);
			return HttpUtils.formatData(dateFormat, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
		//dateFormat.setTotalPages(Long.valueOf(number));
		//dateFormat.setTotalRecords(Long.valueOf(count));
		return HttpUtils.formatData(dateFormat, CODE_OK, MSG_OK, list);
	}
	/**
	 * 监控——媒体舆情
	 * @param pageIndex
	 * @param pageSize
	 * @param userId
	 * @param endTime
	 * @param startTime
	 */
	@ResponseBody
	@RequestMapping("findMedia")
	public String findMedia(HttpServletRequest request,HttpServletResponse response,Integer pageIndex,
			Integer pageSize,String startDate,String endDate,String articleType){
		List<MongodbDate> list = new ArrayList<MongodbDate>();
		StandardDataFormat dateFormat = new StandardDataFormat(CODE_ERROR, MSG_ERROR, list);
		PageView pageView = null;
		//int count = 0;
		//int number = 0;
		Date endTime1 = null;
		Date startTime1 = null;
		try {
			//判断参数
			if (StringUtils.isBlank(articleType)) {
				return HttpUtils.formatData(dateFormat, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
			}
			if (null == pageIndex || pageIndex <= 0) {
				pageIndex = 1;
			}
			if (null == pageSize || pageSize <= 0) {
				pageSize = 15;
			}
			if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
				startTime1 = DateSyncUtil.parse(startDate);
				endTime1 = DateSyncUtil.parse(endDate);
			}
			pageView = new PageView(pageSize, pageIndex);
			//long l = System.currentTimeMillis();
			list = monitoringService.findMedia(pageView, startTime1, endTime1,articleType);
			//System.out.println(System.currentTimeMillis()-l);
			/*if (list.size()>0) {
				//取总数
				count = list.get(0).getCount();
				//计算页码
				number = count % pageView.getPageSize() == 0 ? count
						/ pageView.getPageSize() : count
						/ pageView.getPageSize() + 1;
			}*/
		} catch (Exception e) {
			LoggerUtils.fmtError(getClass(), "查询错误", e.getMessage());
			return HttpUtils.formatData(dateFormat, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
		//dateFormat.setTotalPages(Long.valueOf(number));
		//dateFormat.setTotalRecords(Long.valueOf(count));
		return HttpUtils.formatData(dateFormat, CODE_OK, MSG_OK, list);
	}
	
	/**
	 * 监控——网络舆情
	 * @param pageIndex
	 * @param pageSize
	 * @param userId
	 * @param endTime
	 * @param startTime
	 * @param articleType
	 */
	@ResponseBody
	@RequestMapping("findNetwork")
	public String findNetwork(HttpServletRequest request,HttpServletResponse response,Integer pageIndex,
			Integer pageSize,String startDate,String endDate,String articleType){
		List<MongodbDate> list = new ArrayList<MongodbDate>();
		StandardDataFormat dateFormat = new StandardDataFormat(CODE_ERROR, MSG_ERROR, list);
		PageView pageView = null;
		List<String> typelist = new ArrayList<String>();
		//int count = 0;
		//int number = 0;
		Date endTime1 = null;
		Date startTime1 = null;
		try {
			if (StringUtils.isBlank(articleType)) {
				return HttpUtils.formatData(dateFormat, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
			}
			if (null == pageIndex || pageIndex <= 0) {
				pageIndex = 1;
			}
			if (null == pageSize || pageSize <= 0) {
				pageSize = 15;
			}
			if (null != articleType) {
				typelist = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(articleType);
			}
			if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
				endTime1 = DateSyncUtil.parse(endDate);
				startTime1 = DateSyncUtil.parse(startDate);
			}
			pageView = new PageView(pageSize, pageIndex);
			//long l = System.currentTimeMillis();
			list = monitoringService.findNetwork(pageView, startTime1, endTime1, typelist);
			//System.out.println(System.currentTimeMillis()-l);
			/*if (list.size()>0) {
				//取总数
				count = list.get(0).getCount();
				//计算页码
				number = count % pageView.getPageSize() == 0 ? count
						/ pageView.getPageSize() : count
						/ pageView.getPageSize() + 1;
			}*/
		} catch (Exception e) {
			LoggerUtils.fmtError(getClass(), "查询错误", e.getMessage());
			return HttpUtils.formatData(dateFormat, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
		//dateFormat.setTotalPages(Long.valueOf(number));
		//dateFormat.setTotalRecords(Long.valueOf(count));
		return HttpUtils.formatData(dateFormat, CODE_OK, MSG_OK, list);
	}
	
	/**
	 * 中周舆情搜索
	 * @param pageIndex
	 * @param pageSize
	 * @param articleType
	 * @param title
	 */
	@ResponseBody
	@RequestMapping("findzhongzhouSeek")
	public String findzhongzhouSeek(HttpServletRequest request,HttpServletResponse response,Integer pageIndex,
			Integer pageSize,String articleType,String title,String author){
		List<MongodbDate> list = new ArrayList<MongodbDate>();
		StandardDataFormat dateFormat = new StandardDataFormat(CODE_ERROR, MSG_ERROR, list);
		PageView pageView = null;
		try {
			if (null == pageIndex || pageIndex <= 0) {
				pageIndex = 1;
			}
			if (null == pageSize || pageSize <= 0) {
				pageSize = 15;
			}
			if (StringUtils.isNotBlank(articleType)) {
				//转码
				articleType = EncodingUtils.fixUrlParamEncoding(request, articleType);
			}
			if (StringUtils.isNotBlank(author)) {
				//转码
				author = EncodingUtils.fixUrlParamEncoding(request, author);
			}
			if (StringUtils.isNotBlank(title)) {
				String[] strarr = {"\\","||","&&","$","|","+","(",")","*",".","[","]","?","^","{","}","——","-","_"};
				for (String key : strarr) {
					if (title.contains(key)) {
						title = title.replace(key,"\\"+key);
					}
				}
				//System.out.println(title);
				title = title.replaceAll("\u200b", "");//.replace("(", "\\(").replace(")", "\\)");
				//转码后解决高亮字查询问题
				title = StringUtil.getLikeAppString(transString(request, title));
			}
			pageView = new PageView(pageSize, pageIndex);
			//long l = System.currentTimeMillis();
			list = monitoringService.findzhongzhouSeek(pageView, articleType, title,author);
			//System.out.println(list.get(0).getTitle());
			//System.out.println(System.currentTimeMillis()-l);
		} catch (Exception e) {
			LoggerUtils.fmtError(getClass(), "查询错误", e.getMessage());
			e.printStackTrace();
			System.out.println(e);
			return HttpUtils.formatData(dateFormat, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
		return HttpUtils.formatData(dateFormat, CODE_OK, MSG_OK, list);
	}
	
	/**
	 * 查询微信单条数据
	 * @param request
	 * @param response
	 * @param articleId
	 * @param ifmId
	 */
	@ResponseBody
	@RequestMapping("findSingle")
	public String findSingle(HttpServletRequest request,HttpServletResponse response,String articleId,String ifmId){
		StandardDataFormat dateFormat = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
		MongodbDate date = new MongodbDate();
		try {
			if (StringUtils.isBlank(articleId) && StringUtils.isBlank(ifmId)) {
				return HttpUtils.formatData(dateFormat, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
			}
			date = monitoringService.findSingle(articleId, ifmId);
		} catch (Exception e) {
			LoggerUtils.fmtError(getClass(), "查询错误", e.getMessage());
			e.printStackTrace();
			System.out.println(e);
			return HttpUtils.formatData(dateFormat, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
		return HttpUtils.formatData(dateFormat, CODE_OK, MSG_OK, date);
	}
	
	@RequestMapping("ExportExecl")
	@ResponseBody
	public String ExportExecl(HttpServletRequest request,HttpServletResponse response,String Id){
		StandardDataFormat dateFormat = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
		try {
			//定义表头
			List<String> titles = Arrays.asList("标题","来源","作者","时间","性质");
			//定义字段名
			List<String> paramsName = Arrays.asList("title","websiteName","author","releaseTime","nature");
			List<String> listid = new ArrayList<String>();
			if (StringUtils.isNotBlank(Id)) {
				listid = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(Id);
			}
			List<MongodbDate> list = monitoringService.findByArticleId(listid);
			//输出流
			OutputStream out = null;
			try {
				//获取输出流
				out = response.getOutputStream();
				//清空流
				response.reset();
				//定义响应输出类型
				response.setContentType("application/msexcel");
				//设置输出文件头
				response.setHeader("Content-disposition",
                        "attachment; filename=" + new String("中周舆情信息".getBytes("GBK"), "iso8859-1") + ".xls");
				//调用生成excel方法
				ExcelUtils.exportExcel(titles, paramsName, list, out);
			} catch (Exception e) {
				log.error(e.getMessage());
				e.printStackTrace();
			}finally{
				//关闭流
				out.close();
			}
		} catch (Exception e) {
			LoggerUtils.fmtError(getClass(), "导出错误", e.getMessage());
			e.printStackTrace();
			System.out.println(e);
			return HttpUtils.formatData(dateFormat, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
		return HttpUtils.formatData(dateFormat, CODE_OK, MSG_OK, null);
	}
	
}
